<?php
/**
 * $Id: votes_controller.php 26 2010-09-07 11:45:41Z shrey $
 * 
 * This file can not be redistributed to anyone without the permission of Giga Promoters
 * Copyright 2005 - 2008, Giga Promoters
 * 						  608 Aggarwal Cyber Plaza
 *						  Netaji Subhash Place, Delhi - 110034
 *						  www.gigapromoters.com
 * 
 *
 * @version 			$Rev: 26 $
 * @lastModifiedBy		$LastChangedBy: shrey $
 * @lastChanged			$Date: 2010-09-07 17:15:41 +0530 (Tue, 07 Sep 2010) $
 * @copyright 			Giga Promoters (www.gigapromoters.com)
 * 
 */

class VotesController extends AppController {

	var $name = 'Votes';
	var $components = array('Email');

	function add($type, $item_id, $score)
	{
		$newVote = array();
		$newVote['type'] = $type;
		$newVote['item_id'] = $item_id;
		$newVote['score'] = $score;
		$authedUser = $this->Session->read('Auth.User');
		//pr(Configure::read('viewPaths'));
		// check if guest votes are allowed
		if(Configure::read('Vote.allowGuests')==false && !$authedUser )
		{
			$this->errorMsg(__('Please signin to continue.'));
			$error =1;
		}
		elseif($authedUser)
		{
			$newVote['user_id'] = $authedUser['id'];
			$oldVote = $this->Vote->find('first',array('conditions'=>array('Vote.user_id'=>$authedUser['id'],'Vote.item_id'=>$item_id, 'Vote.type'=>$type)));
			$voteId = null;
			if(isset($oldVote['Vote']['id']))
				$voteId = $oldVote['Vote']['id'];
			if($voteId && Cr('Vote.allowVoteChange') == false)
			{
				$this->errorMsg(sprintf(__('You have already voted for this %s.'),low($type)));
				$error =1;
			}else
			{
				$newVote['id'] = $voteId;
			}
		}
		if(empty($error) || $error!=1)
		{
			$this->_saveVote($newVote);
		}
		$voteUp = $this->Vote->getVotesCount($type,$item_id,Vote::TYPE_UP);
		$voteDown = $this->Vote->getVotesCount($type,$item_id,Vote::TYPE_DOWN);
		$this->set(compact('voteUp','voteDown'));
	}

	function _saveVote($newVote)
	{
		$this->Vote->create();
		if($this->Vote->save($newVote))
		{
			$this->success(__('Thanks for voting.'));
			callHooks('afterVote','.+',$this,$newVote);
		}
		else {
			$this->errorMsg(__('Unable to accept your vote.'));
		}		
		$this->set('voteData',$newVote);
	}
}
?>